﻿using NLog;
using NLog.LayoutRenderers;
using System;
using System.Diagnostics;
using System.Text;

namespace GetMan.Core.NLogRender
{
    [LayoutRenderer("process-cpu-usage")]
    public class ProcessCpuUsageLayoutRenderer : LayoutRenderer
    {
        private static readonly Process CurrentProcess = Process.GetCurrentProcess();
        private static DateTime _lastSampleTime = DateTime.Now;
        private static TimeSpan _lastProcessorTime = CurrentProcess.TotalProcessorTime;
        protected override void Append(StringBuilder builder, LogEventInfo logEvent)
        {
            // 计算 CPU 使用率
            var now = DateTime.Now;
            var elapsedTime = now - _lastSampleTime;
            var processorTime = CurrentProcess.TotalProcessorTime;
            var cpuUsage = (processorTime - _lastProcessorTime).TotalMilliseconds / elapsedTime.TotalMilliseconds / Environment.ProcessorCount * 100;

            // 更新上次采样时间和处理器时间
            _lastSampleTime = now;
            _lastProcessorTime = processorTime;
            builder.Append($"{cpuUsage:0.0}%");
        }
    }
}